package com.example.controller;

import com.example.dto.NovelDTO;
import com.example.dto.PageDTO;
import com.example.entity.Novel;
import com.example.query.NovelQuery;
import com.example.result.Result;
import com.example.service.INovelService;
import com.example.vo.NovelVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Set;

@RestController
@RequestMapping("/novel")
@Slf4j
@RequiredArgsConstructor
public class NovelController {

    private final INovelService novelService;
    private final RedisTemplate redisTemplate;

    /*
    * 新增小说
    * @param novelDTO
    * @return
    * */
    @PostMapping("/add")
    public Result addNovel(@RequestBody NovelDTO novelDTO){
        log.info("新增小说"+novelDTO);
        novelService.addNovel(novelDTO);
//        clearCache();
        return Result.success();
    }

    /*
    * 查询小说(分页)
    * @param novelQuery
    * @return
    * */
    @GetMapping("/page")
    public Result<PageDTO<NovelVO>> page(NovelQuery novelQuery){
        log.info("小说信息分页查询:" + novelQuery);
        return novelService.QueryNovelpage(novelQuery);
    }

    /*
    * 删除小说
    * @param id
    * @return
    * */
    @DeleteMapping
    public Result delete(Long id){
        log.info("删除小说:" + id);
        novelService.removeById(id);
        return Result.success();
    }

    /*
    * 修改小说
    * @param novelDTO
    * @return
    * */
    @PutMapping
    public Result update(@RequestBody NovelDTO novelDTO){
        log.info("修改小说:" + novelDTO);
        novelService.updateNovel(novelDTO);
//        clearCache();
        return Result.success();
    }

    /*
    * 根据id查询小说
    * @param id
    * @return
    * */
    @GetMapping("/{id}")
    public Result<Novel> info(@PathVariable Long id){
        log.info("查询小说:" + id);
        return Result.success(novelService.getById(id));
    }

    /*
    * 清理缓存
    * */
    private void clearCache() {
        Set keys = redisTemplate.keys("novels");
        redisTemplate.delete(keys);
    }
}
